package com.berwin.network;

import android.util.Log;

import com.berwin.listener.FileTransferListener;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.RoundingMode;
import java.net.Socket;
import java.text.DecimalFormat;

public class SessionFile {


    private boolean isRunning;
    private Socket socket;
    // 下载保存的路径
    private String downloadDirectory;
    // 上传文件
    private String uploadFile;

    private String host;
    private int port;

    private FileTransferListener listener;

    public SessionFile(String host, int port, FileTransferListener listener) {
        this.host = host;
        this.port = port;
        this.listener = listener;
    }

    /**
     * 上传文件
     *
     * @param uploadFile
     */
    public void upload(final String uploadFile) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                SessionFile.this.uploadFile = uploadFile;

                try {
                    File file = new File(SessionFile.this.uploadFile);
                    if (file.exists()) {
                        FileInputStream fis = new FileInputStream(file);
                        DataOutputStream dos = new DataOutputStream(SessionFile.this.socket.getOutputStream());

                        // 文件名和长度
                        dos.writeUTF(file.getName());
                        dos.flush();
                        dos.writeLong(file.length());
                        dos.flush();

                        // 开始传输文件
                        Log.i("SessionFile", "======== 开始传输文件 ========");
                        if (listener != null)
                            listener.onStart(SessionFile.this, file.getParent(), file.getName());
                        byte[] bytes = new byte[1024];
                        int length = 0;
                        long progress = 0;
                        while ((length = fis.read(bytes, 0, bytes.length)) != -1) {
                            dos.write(bytes, 0, length);
                            dos.flush();
                            progress += length;

                            int percent = (int) (100 * progress / file.length());
                            if (listener != null)
                                listener.onProgress(SessionFile.this, percent);
                            Log.i("SessionFile", "| " + percent + "% |");
                        }
                        fis.close();
                        Log.i("SessionFile", "======== 文件传输成功 ========");
                        if (listener != null)
                            listener.onFinished(SessionFile.this, file.getParent(), file.getName());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (listener != null)
                        listener.onError(SessionFile.this, e.toString());
                }
//            finally {
//                try {
//                    if (fis != null)
//                        fis.close();
//                    if (dos != null)
//                        dos.close();
//                    SessionFile.this.socket.close();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
            }
        }).start();
    }

    /**
     * 下载文件
     *
     * @param directory
     */
    public void start(String directory) {
        this.downloadDirectory = directory;
        new Thread(new Runnable() {
            @Override
            public void run() {
                SessionFile self = SessionFile.this;
                try {
                    SessionFile.this.socket = new Socket(SessionFile.this.host, SessionFile.this.port);
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
                self.isRunning = true;
                while (SessionFile.this.isRunning) {
                    try {
                        DataInputStream dis = new DataInputStream(socket.getInputStream());
                        // 文件名和长度
                        String fileName = dis.readUTF();
                        long fileLength = dis.readLong();
                        File fileDir = new File(SessionFile.this.downloadDirectory);
                        if (!fileDir.exists()) {
                            fileDir.mkdir();
                        }
                        if (listener != null)
                            listener.onStart(SessionFile.this, fileDir.getParent(), fileName);
                        File file = new File(fileDir.getAbsolutePath() + File.separatorChar + fileName);
                        FileOutputStream fos = new FileOutputStream(file);

                        // 开始接收文件
                        byte[] bytes = new byte[1024];
                        int length = 0;
                        long progress = 0;
                        while ((length = dis.read(bytes, 0, bytes.length)) != -1) {
                            fos.write(bytes, 0, length);
                            fos.flush();
                            progress += length;
                            int percent = (int) (100 * progress / fileLength);
                            if (listener != null)
                                listener.onProgress(SessionFile.this, percent);
                            if (progress >= fileLength)
                                break;
                        }
                        fos.close();
                        Log.i("SessionFile", "======== 文件接收成功 [File Name：" + fileName + "] [Size：" + getFormatFileSize(fileLength) + "] ========");
                        if (listener != null)
                            listener.onFinished(SessionFile.this, fileDir.getParent(), fileName);
                    } catch (Exception e) {
                        e.printStackTrace();
                        SessionFile.this.isRunning = false;
                        if (listener != null)
                            listener.onError(SessionFile.this, e.toString());
                    }
                }
//            finally {
//                try {
//                    if (fos != null)
//                        fos.close();
//                    if (dis != null)
//                        dis.close();
//                    socket.close();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//            }
            }
        }).start();
    }

    public FileTransferListener getListener() {
        return listener;
    }

    public void setListener(FileTransferListener listener) {
        this.listener = listener;
    }

    private static DecimalFormat df = null;

    static {
        // 设置数字格式，保留一位有效小数
        df = new DecimalFormat("#0.0");
        df.setRoundingMode(RoundingMode.HALF_UP);
        df.setMinimumFractionDigits(1);
        df.setMaximumFractionDigits(1);
    }

    /**
     * 格式化文件大小
     *
     * @param length
     * @return
     */
    private String getFormatFileSize(long length) {
        double size = ((double) length) / (1 << 30);
        if (size >= 1) {
            return df.format(size) + "GB";
        }
        size = ((double) length) / (1 << 20);
        if (size >= 1) {
            return df.format(size) + "MB";
        }
        size = ((double) length) / (1 << 10);
        if (size >= 1) {
            return df.format(size) + "KB";
        }
        return length + "B";

    }
}
